﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Text.RegularExpressions;
using tmAsk.User;

namespace tmAsk.Common
{
    public class function : tmAsk.Data.MakeHtml
    {
        static tmAsk.Data.MakehtmlSQL SQL = new tmAsk.Data.MakehtmlSQL();
        public function()
        {
        }

        public override string functionhtml(string html, string str)
        {
            switch (html)
            {
                case "CutString"://变量名称
                    string[] arr = str.Split(',');
                    return CutString(arr[0], arr[arr.Length - 1]);//自定义函数，与模板相同
                case "Count_user":
                    return Count_user(str);
                case "md5":
                    return (new function()).Md5(str);
                case "LikeQuestion":
                    return (new alldata()).LikeQuestion(str);
                case "GetRatio":
                    return (new alldata()).GetRatio(str);
                case "Gethidden":
                    return Gethidden(str);
                case "GetAskID":
                    return GetAskID(str);
                case "Replace":
                    return replacehtml(str);
                case "GetSelected":
                    string[] arrSelect = str.Split(',');
                    return (new alldata()).GetSelected(arrSelect[0], arrSelect[1]);
                case "Getlink":
                    string[] link = str.Split(',');
                    return Getlink(link[0], link[1]);
                case "GetClassName":
                    return (new alldata()).GetClassName(str);
                case "searchkey":
                    return Searchkey(str);
                case "GetQuestionImage":
                    return GetQuestionImage(str);
                case "Isaskupload":
                    return Isaskupload(str);
                case "Isreupload":
                    return Isaskupload(str);
                case "Config_askupload":
                    return Config_askupload(str);
                case "Config_reupload":
                    return Config_reupload(str);
                case "getsorce":
                    return getsorce();
                case "Isaskvideo":
                    return Isaskvideo(str);
                case "getmmdd": //自定义函数，获得月/日期
                    return getmmdd(str);
                case "GetLastRe":
                    string[] lre = str.Split(',');
                    return GetLastRe(lre[0], lre[lre.Length - 1]);
                case "GetUserClass":
                    return GetUserClass(str);
                case "GetUserClassID":
                    return GetUserClassID(str);
                case "GetLevelName":
                    return GetLevelName(str);
            }
            return "";
        }

        #region 模板系统函数
        //模板函数
        private string GetQuestionImage(string str)
        {
            if (str.Trim() == "")
            {
                return " \" style=\"display:none\"";
            }
            return str;
        }

        private string Config_askupload(string str)
        {
            if (alldata.Config_askupload == "0")
            {
                return " 附件上传：<input type=\"file\" id=\"fileUpload\" name=\"fileUpload\" /> 只支持图片";
            }
            return "";
        }

        private string Config_reupload(string str)
        {
            if (alldata.Config_reupload == "0")
            {
                return "图片上传：<input type=\"file\" id=\"fileUpload\" name=\"fileUpload\" />";
            }
            return "";
        }

        private string Isaskupload(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return "参考附件：<a href='" + GetQuestionImage(str) + "' target='_blank'><img alt='参考图片' width=\"50\" width=\"50\" src=\"" + GetQuestionImage(str) + "\" /></a>";
            }
            return "";
        }

        private string Isaskvideo(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return "<a id=\"showVideo\" href=\"/aspx/b_video.aspx?url=" + str + "\" title=\"视频预览\" class=\"boxy\"><img src=\"images/video.jpg\" border=\"0\" alt=\"点击观看视频\" /> 视频点击观看</a>";
            }
            return "";
        }

        private string Isreupload(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return "参考附件：<a href='" + GetQuestionImage(str) + "' target='_blank'><img alt='参考图片' width=\"50\" width=\"50\" src=\"" + GetQuestionImage(str) + "\" /></a>";
            }
            return "";
        }

        private string getmmdd(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return Convert.ToDateTime(str).ToString("MM/dd");
            }
            return "";
        }

        private string GetLastRe(string str, string t)
        {
            DataTable lc = SQL.GetList("SELECT TOP 1 * FROM b_review WHERE r_userid = '" + str + "' ORDER BY r_id DESC").Tables[0];
            DataTable lcc = SQL.GetList("SELECT TOP 1 * FROM b_ask WHERE a_id = '" + lc.Rows[0]["a_id"].ToString() + "'").Tables[0];
            return "<a href=\"/?ask-" + lcc.Rows[0]["a_id"].ToString() + "\" title=\"" + lcc.Rows[0]["a_title"].ToString() + "\">" + CutString(lcc.Rows[0]["a_title"].ToString(), t) + "</a>";
        }

        private string Searchkey(string str)
        {
            string[] t = str.Split('|');
            return t[0].ToLower().Replace(t[1].ToLower().ToString(), "<span style=\"color:red;\">" + t[1].ToLower() + "</span>");
        }

        private string replacehtml(string str)
        {
            string[] t = str.Split(',');
            string longstring = t[0].ToLower();
            if (t[0].Length > 15)
            {
                longstring = longstring.Substring(0, 15) + "...";
            }
            if (t.Length > 2)
            {
                string oldstring = t[1].ToLower();
                string newstring = t[2].ToLower();
                if (oldstring != "" && newstring != "")
                {
                    return longstring.Replace(t[1].ToLower(), t[2].ToLower()).ToString();
                }
            }
            return longstring;
        }


        /// <summary>
        /// 弹出提示信息
        /// </summary>
        /// <param name="num">1:没有返回值2:有返回地址3:直接关闭当期窗口4:返回上一级5:直接跳转</param>
        /// <param name="str">弹出的内容</param>
        /// <param name="url">跳转的路径</param>
        /// <returns></returns>
        public static string alert_text(int num, string str, string url)
        {
            switch (num)
            {
                case 1://普通的弹出，没有返回值
                    return "<script>alert('" + str + "');</script>";
                case 2://普通的弹出窗口，有返回地址
                    return "<script>alert('" + str + "');location='" + url + "';</script>";
                case 3://普通的弹出窗口，直接关闭当期窗口
                    return "<script>alert('" + str + "');location='javascript:window.close();';</script>";
                case 4://普通的弹出窗口，返回上一级
                    return "<script>alert('" + str + "');location='javascript:window.history.go(-1);';</script>";
                case 5:
                    return "<script>location='" + url + "';</script>";
            }

            return "";
        }


        public static bool GetAskIscheck(string askid)
        {
            tmAsk.Data.MakehtmlSQL SQL = new tmAsk.Data.MakehtmlSQL();
            DataRow ic = SQL.GetList("b_ask", "a_id='" + askid + "'", "a_ischeck").Tables[0].Rows[0];

            bool check = Convert.ToBoolean(ic[0]);

            return check;
        }

        //获得帖子编号
        private string GetAskID(string str)
        {
            string askid = str;
            return askid;
        }

        //获得分类管理员管理分类
        private string GetUserClass(string str)
        {
            tmAsk.Data.MakehtmlSQL SQL = new tmAsk.Data.MakehtmlSQL();
            DataRow uc = SQL.GetList("B_user", "u_id='" + str + "'", "u_userclass").Tables[0].Rows[0];
            if (uc[0].ToString() == "" || uc[0].ToString() == null)
            {
                return "未分配";
            }
            DataRow cl = SQL.GetList("B_askClass", "a_classid='" + uc["u_userclass"].ToString() + "'", "a_className").Tables[0].Rows[0];
            return cl[0].ToString();
        }

        //获得分类管理员管理分类ID
        private string GetUserClassID(string str)
        {
            tmAsk.Data.MakehtmlSQL SQL = new tmAsk.Data.MakehtmlSQL();
            DataRow uc = SQL.GetList("B_user", "u_id='" + str + "'", "u_userclass").Tables[0].Rows[0];
            if (uc[0].ToString() == "" || uc[0].ToString() == null)
            {
                return "未分配";
            }
            DataRow cl = SQL.GetList("B_askClass", "a_classid='" + uc["u_userclass"].ToString() + "'", "a_classid").Tables[0].Rows[0];
            return cl[0].ToString();
        }

        //获得等级名
        private string GetLevelName(string str)
        {
            tmAsk.Data.MakehtmlSQL SQL = new tmAsk.Data.MakehtmlSQL();
            DataRow uc = SQL.GetList("B_userLevel", "u_level='" + str + "'", "u_title").Tables[0].Rows[0];
            return uc[0].ToString();
        }

        //模板函数
        private string Gethidden(string str)
        {
            string[] t = str.Split(',');
            if (t.Length > 0)
            {
                if (Convert.ToInt16(t[1]) > 0)
                {
                    return "匿名";
                }
                else
                {
                    return t[0].ToString();
                }
            }

            return "";
        }

        //输入框替换
        public static string TxtReplace(string str)
        {
            return str.Trim().Replace("'", "`");
        }

        //判断是否数字
        public static bool isNumber(params string[] param)
        {
            foreach (string item in param)
            {
                try
                {
                    Convert.ToInt32(item);
                }
                catch (Exception)
                {
                    return true;
                }
            }
            return false;
        }

        //html内容转换
        public static string HTMLEncode(string fString)
        {
            if (fString != string.Empty)
            {
                // fString = HttpContext.Current.Server.HtmlEncode(fString);
                //fString = fString.Replace("\r\n", "<br /> ");
                //fString = fString.Replace("\t", "&nbsp;");
                fString = fString.Replace("<srcipt", "非法数据");
                fString = fString.Replace("iframe", "非法数据");

            }
            return (fString);
        }

        //截取字符串
        public static string CutString(string str, string t)//截取字符长度
        {
            try
            {
                if (str.Length > Convert.ToInt32(t))
                {
                    return str.Substring(0, Convert.ToInt32(t)) + "…";
                }
            }
            catch { }
            return str;
        }

        public static string Count_user(string str)
        {
            string uid = (str.Split(','))[0];
            string target = (str.Split(','))[1];
            string count = "";
            switch (target)
            {
                case "ask":
                    count = SQL.GetListcount("b_ask", "u_id=" + uid).ToString();
                    break;
                case "reply":
                    count = SQL.GetListcount("b_review", "r_userid=" + uid).ToString();
                    break;
                case "good":
                    double recount = SQL.GetListcount("b_review", "r_userid=" + uid);
                    double isgood = SQL.GetListcount("b_review", "r_userid=" + uid + " and r_isGood=1");
                    try
                    {
                        count = (Convert.ToInt32(isgood / recount * 100)).ToString() + "%";
                    }
                    catch
                    {
                        return "0%";
                    }
                    break;
            }
            return count;
        }

        //判断是否为空
        public static bool CheckNull(params object[] name)
        {
            foreach (object item in name)
            {
                if (object.Equals(item, null))
                {
                    return false;
                }
                if (string.IsNullOrEmpty(item.ToString()))
                {
                    return false;
                }
            }
            return true;

        }

        //判断是否为空
        public static bool CheckNullnum(params object[] name)
        {
            foreach (object item in name)
            {
                if (object.Equals(item, null))
                {
                    return false;
                }
                if (string.IsNullOrEmpty(item.ToString()))
                {
                    return false;
                }

                try
                {
                    Convert.ToInt16(item);
                }
                catch
                {
                    return false;
                }
            }
            return true;

        }

        //系统连接机制
        public string Getlink(string item, string parm)
        {
            switch (item)
            {
                case "default":
                    return "/?default";
                case "help":
                    return "/?help-" + parm;
                case "search":
                    return "/?search-" + parm;
                case "notice":
                    return "/?notice-" + parm;
                case "ask":
                    return "/?ask-" + parm;
                case "reg":
                    return "/?reg";
                case "login":
                    return "/?login";
                case "class":
                    return "/?class-" + parm;
                case "add":
                    return "/?question";
                case "list":
                    return "/?list";
                case "listing":
                    return "/?listing";
                case "template":
                    return alldata.Config_template;
            }
            return "/?default";
        }

        //模板调取列表
        public string Gettemplate(int i)
        {
            string html = Get_html(HttpContext.Current.Server.MapPath(@"~/") + (new alldata()).Gettemplate(i));
            string template = alldata.Config_template;//模板路径

            ////处理图片地址
            Regex reg = new Regex(@"(?is)(?<=<img\s+src=(['""]?))(?!http://)(?=[^'""\s>]+\1)");
            html = reg.Replace(html, template);
            reg = null;

            //处理CSS样式
            Regex regC = new Regex(@"(?is)(?<=<link\s+href=(['""]?))(?!http://)(?=[^'""\s>]+\1)");
            html = regC.Replace(html, template);
            regC = null;

            //处理JS脚本
            Regex regJ = new Regex(@"(?is)(?<=<script\s+src=(['""]?))(?!http://)(?!/)(?=[^'""\s>]+\1)");
            html = regJ.Replace(html, template);
            regJ = null;

            return html;
        }
        //模板调取带参数
        public string Gettemplate(int i, string oldstr, string newstr)
        {
            string html = Get_html(HttpContext.Current.Server.MapPath(@"~/") + (new alldata()).Gettemplate(i), oldstr, newstr);
            string template = alldata.Config_template;//模板路径

            ////处理图片地址
            Regex reg = new Regex(@"(?is)(?<=<img\s+src=(['""]?))(?!http://)(?=[^'""\s>]+\1)");
            html = reg.Replace(html, template);
            reg = null;

            //处理CSS样式
            Regex regC = new Regex(@"(?is)(?<=<link\s+href=(['""]?))(?!http://)(?=[^'""\s>]+\1)");
            html = regC.Replace(html, template);
            regC = null;

            //处理JS脚本
            Regex regJ = new Regex(@"(?is)(?<=<script\s+src=(['""]?))(?!http://)(?!/)(?=[^'""\s>]+\1)");
            html = regJ.Replace(html, template);
            regJ = null;

            return html;
        }
        //模板调取分页
        public string Gettemplate(int i, string pagestr, int pageint, string pageurl, string oldstr, string newstr)
        {
            string html = Get_page(HttpContext.Current.Server.MapPath(@"~/") + (new alldata()).Gettemplate(i), oldstr, newstr, pagestr, pageint, pageurl);
            string template = alldata.Config_template;//模板路径

            ////处理图片地址
            Regex reg = new Regex(@"(?is)(?<=<img\s+src=(['""]?))(?!http://)(?=[^'""\s>]+\1)");
            html = reg.Replace(html, template);
            reg = null;

            //处理CSS样式
            Regex regC = new Regex(@"(?is)(?<=<link\s+href=(['""]?))(?!http://)(?=[^'""\s>]+\1)");
            html = regC.Replace(html, template);
            regC = null;

            //处理JS脚本
            Regex regJ = new Regex(@"(?is)(?<=<script\s+src=(['""]?))(?!http://)(?!/)(?=[^'""\s>]+\1)");
            html = regJ.Replace(html, template);
            regJ = null;

            return html;
        }

        //模板调取分页带参数
        public string Gettemplate(int i, string pagestr, int pageint, string pageurl)
        {
            string html = Get_page(HttpContext.Current.Server.MapPath(@"~/") + (new alldata()).Gettemplate(i), pagestr, pageint, pageurl);
            string template = alldata.Config_template;//模板路径

            ////处理图片地址
            Regex reg = new Regex(@"(?is)(?<=<img\s+src=(['""]?))(?!http://)(?=[^'""\s>]+\1)");
            html = reg.Replace(html, template);
            reg = null;

            //处理CSS样式
            Regex regC = new Regex(@"(?is)(?<=<link\s+href=(['""]?))(?!http://)(?=[^'""\s>]+\1)");
            html = regC.Replace(html, template);
            regC = null;

            //处理JS脚本
            Regex regJ = new Regex(@"(?is)(?<=<script\s+src=(['""]?))(?!http://)(?!/)(?=[^'""\s>]+\1)");
            html = regJ.Replace(html, template);
            regJ = null;

            return html;
        }


        #endregion

        #region 系统身份验证

        //获取登录身份
        public static string Getcookies()
        {
            if (!object.Equals(HttpContext.Current.Session["UserLogin"], null))
            {
                return HttpContext.Current.Server.UrlDecode(HttpContext.Current.Session["UserLogin"].ToString());
            }
            return "";
        }

        //写入cookies
        public static void WriteCookie(string id, int days)
        {
            id = HttpContext.Current.Server.UrlEncode(id);
            HttpCookie cookie = new HttpCookie("user");
            DateTime dt = DateTime.Now;
            cookie.Values.Add("uid", id);
            switch (days)
            {
                case 0:
                    cookie.Values.Add("Time", null);
                    break;
                case 30:
                    cookie.Values.Add("Time", dt.AddMinutes(30).ToString());
                    cookie.Expires = dt.AddMinutes(30);
                    break;
                case 60:
                    cookie.Values.Add("Time", dt.AddHours(1).ToString());
                    cookie.Expires = dt.AddHours(1);
                    break;
                case 24:
                    cookie.Values.Add("Time", dt.AddDays(1).ToString());
                    cookie.Expires = dt.AddDays(1);
                    break;
                case 31:
                    cookie.Values.Add("Time", dt.AddMinutes(1).ToString());
                    cookie.Expires = dt.AddMonths(1);
                    break;
                case 365:
                    cookie.Values.Add("Time", dt.AddYears(1).ToString());
                    cookie.Expires = dt.AddYears(1);
                    break;
                default:
                    cookie.Values.Add("Time", null);
                    break;
            }
            HttpContext.Current.Response.AppendCookie(cookie);

            //HttpContext.Current.Response.Cookies.Add(cookie);
        }

        //删除全部Cookie
        public static void ClearSession()
        {
            HttpContext.Current.Session.RemoveAll();
            int limit = HttpContext.Current.Request.Cookies.Count;
            if (limit > 0)
            {
                for (int i = 0; i < limit; i++)
                {
                    string cookiesName = HttpContext.Current.Request.Cookies[i].Name;
                    HttpCookie cookie = new HttpCookie(cookiesName);
                    cookie.Expires = DateTime.Now;
                   // HttpContext.Current.Request.Cookies.Add(cookie);
                }
            }
        }

        //判断是否登录
        public static void CheckUserLogin()
        {
            if (HttpContext.Current.Session["UserLogin"] == null)
            {
                HttpContext.Current.Response.Write("<script>parent.location='?login';</script>");
                HttpContext.Current.Response.End();
            }
        }

        //检查Session是否存在UserLogin 不存在返回false
        public static bool CheckSession()
        {
            if (object.Equals(HttpContext.Current.Session["UserLogin"], null))
            {
                return false;
            }
            return true;
        }

        //已登录情况下 替换Session中UserLogin 
        public static bool CheckCookie(string UserName)
        {//如果Session为空 就自动注册一个会员
            if (HttpContext.Current.Session["UserLogin"] == null)
            {
                if (!object.Equals(HttpContext.Current.Request.Cookies["user"], null))
                {
                    if (!object.Equals(HttpContext.Current.Request.Cookies["user"]["uid"], null))
                    {
                        HttpContext.Current.Session["UserLogin"] = HttpContext.Current.Request.Cookies["user"]["uid"];
                        return true;
                    }
                }
                HttpContext.Current.Session["UserLogin"] = UserName;
                return false;
            }
            else
            {
                return true;
            }
        }

        //判断管理员是否登录
        public static void CheckAdminLogin()
        {
            if (object.Equals(HttpContext.Current.Session["adminName"], null))
            {
                HttpContext.Current.Response.Write("<script>parent.location='login.aspx';</script>");
                HttpContext.Current.Response.End();
            }
        }
        #endregion

        #region 获取随机数字和字母
        /// <summary>        
        /// 数字和字母随机数        
        /// </summary>        
        /// <param name="length">生成长度</param> 
        /// 
        /// <returns>返回指定长度的数字和字母的随机串</returns> 
        public static string RndCode(int length)
        {
            int _RandIndex = 0;
            if (_RandIndex >= 1000000) _RandIndex = 1;
            char[] arrChar = new char[] { 'a', 'b', 'd', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 'q', 's', 't', 'u', 'v', 'w', 'z', 'y', 'x', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            System.Text.StringBuilder num = new System.Text.StringBuilder();
            Random rnd = new Random(DateTime.Now.Millisecond + _RandIndex);
            for (int i = 0; i < length; i++)
            {
                num.Append(arrChar[rnd.Next(0, arrChar.Length)].ToString());
            }
            return num.ToString();
        }

        public static IList<string> RndCodeList(int len)
        {
            IList<string> list = new List<string>();
            for (int i = 0; i < len; i++) list.Add(RndCode(len));
            return list;
        }

        private string getsorce()
        {
            if (CheckSession())
            {
                string username = Getcookies();
                return (new alldata()).usersorce(username);

            }
            return "";
        }

        #endregion

        public static string NoHTML(string Htmlstring)
        {
            //删除脚本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim().Replace("'", "`");
            return Htmlstring;
        }

        public static string getClientIP()
        {
            string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (ip == null || ip == "")
            {
                ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            return ip;
        }
    }
}
